package com.ys.everydaynews.view

import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class ItemDragHelperListener : ItemTouchHelper.Callback() {
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val dragFlags: Int
        val manager: RecyclerView.LayoutManager? = recyclerView.layoutManager
        dragFlags = if (manager is GridLayoutManager || manager is StaggeredGridLayoutManager) {
            ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        } else {
            ItemTouchHelper.UP or ItemTouchHelper.DOWN
        }
        //如果需要支持滑动删除，swipeFlages=ItemTouchHelper.START | ItemTouchHelper.END
        val swipeFlages = 0
        return makeMovementFlags(dragFlags, swipeFlages)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        if (viewHolder.itemViewType !== target.itemViewType) {
            return false
        }
        if (recyclerView.adapter is OnItemMoveListener) {
            val listener: OnItemMoveListener = recyclerView.adapter as OnItemMoveListener
            listener.onItemMove(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition)
        }
        return true
    }

    //当前target对应的item是否允许移动
    override fun canDropOver(
        recyclerView: RecyclerView,
        current: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return true
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (viewHolder is OnItemThListener) {
                viewHolder.onItemSelected()
            }
        }
        super.onSelectedChanged(viewHolder, actionState)
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        if (viewHolder is OnItemThListener) {
            viewHolder.onItemFinish()
        }
        super.clearView(recyclerView, viewHolder)
    }

    //不让使用长拖拽
    override fun isLongPressDragEnabled(): Boolean {
        return false
    }

    //不让使用侧滑
    override fun isItemViewSwipeEnabled(): Boolean {
        return false
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

    }
}